import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import moment from 'moment';

import { timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Descriptions,
  Button,
  Table,
  message,
  Tooltip,
} from 'antd';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;
const time = new Date().getTime();
const lastWeek = time - 1000 * 60 * 60 * 24 * 7;

interface OrderInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: AnimationPlaybackEventInit;
  INITINFO: any;
  location: {
    search?: any;
  };
}

interface OrderInfoState {
  searchValues: any;
  rowId: number;
}

@connect(({
  partitionOrder: { dataInfo, statusList },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  statusList,
  INITINFO,
}))

class OrderInfoElem extends Component<OrderInfoProps, OrderInfoState> {
  columns = [
    {
      title: '　运单号',
      dataIndex: 'expCode',
      width: 160,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '开箱密码',
      dataIndex: 'openCode',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '收件人手机',
      dataIndex: 'consigneePhone',
      width: 120,
    },
    {
      title: '投递人手机',
      dataIndex: 'courierPhone',
      width: 120,
    },
    {
      title: '入库时间',
      dataIndex: 'inTime',
      width: 160,
    },
    {
      title: '出库时间',
      dataIndex: 'outTime',
      width: 160,
      render: (val: string) => val || '--',
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '批次编号',
      dataIndex: 'batchName',
      width: 100,
    },
    {
      title: '投递类型',
      dataIndex: 'deliveryWayName',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '订单状态',
      dataIndex: 'statusName',
      width: 100,
    },
    {
      title: '短信状态',
      dataIndex: 'smsStatus',
      width: 100,
    },
  ];

  state: OrderInfoState = {
    rowId: 0,
    searchValues: {
      startTime: `${moment(lastWeek).format('YYYY-MM-DD')} 00:00:00`,
      endTime: '',
      expCode: '',
      layerId: '',
      expressId: '',
      consigneePhone: '',
      status: '',
      pageIndex: 1,
      pageSize: 20,
    },
  };

  componentDidMount() {
    const { location: { search } } = this.props;
    const { searchValues } = this.state;

    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const params = { ...searchValues, layerId: query.layerId };

    this.setState({ searchValues: params }, () => this.fetchAction('fetch', params));
    this.fetchAction('common/fetchExpressList');
    this.fetchAction('fetchStatus');
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      if (values.seqNo && !values.batchDate) {
        message.error('请选择批次日期');
        return;
      }
      if (values.batchDate && !values.seqNo) {
        message.error('请输入批次编号');
        return;
      }

      const { startAndEndDate } = values;
      const format = 'YYYY-MM-DD';
      const startTime = startAndEndDate ? `${moment(startAndEndDate[0]).format(format)} 00:00:00` : '';
      const endTime = startAndEndDate ? `${moment(startAndEndDate[1]).format(format)} 23:59:59` : '';
      const { searchValues } = this.state;
      const params = {
        ...searchValues,
        ...values,
        expressId: values.expressId || '',
        status: values.status || '',
        startTime,
        endTime,
        batchDate: values.batchDate && `${moment(values.batchDate).format(format)}`,
        pageIndex: 1,
        pageSize: 20,
      };

      delete params.startAndEndDate;
      this.setState({ searchValues: params }, () => this.fetchAction('fetch', params));
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    this.setState({ searchValues: params }, () => this.fetchAction('fetch', params));
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `partitionOrder/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      statusList,
      INITINFO: { expressList },
      location: { search },
    }: any = this.props;

    const query = qs.parse(search, { ignoreQueryPrefix: true });

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Descriptions column={4}>
                <Descriptions.Item label="货架/地堆名称">{query.name}</Descriptions.Item>
                <Descriptions.Item label="货架/地堆编号">{query.code}</Descriptions.Item>
                <Descriptions.Item label="　　分区编号">{query?.layer}</Descriptions.Item>
                <Descriptions.Item label="　　　　描述">{query?.desc}</Descriptions.Item>
              </Descriptions>
            </Row>
            <Row gutter={12}>
              <Col md={12} sm={24}>
                <Item label="起止时间" colon={false}>
                  {getFieldDecorator('startAndEndDate', {
                    initialValue: [moment(new Date(lastWeek), 'YYYY-MM-DD')],
                  })(
                    <RangePicker
                      disabledDate={timeLimit}
                      placeholder={['开始时间', '截止时间']}
                      format={['YYYY-MM-DD', 'YYYY-MM-DD']}
                      style={{ width: '100%' }}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                          moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                        ],
                      }}
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="快递公司" colon={false}>
                  {getFieldDecorator('expressId', { initialValue: 0 })(
                    <Select placeholder="请选择">
                      <Option value={0}>全部</Option>
                      {expressList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　运单号" colon={false}>
                  {getFieldDecorator('expCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="订单状态" colon={false}>
                  {getFieldDecorator('status', { initialValue: 0 })(
                    <Select placeholder="请选择">
                      {statusList.map((item: any) => (
                        <Option value={item.value} key={item.value}>{item.label}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="批次日期" colon={false}>
                  {getFieldDecorator('batchDate')(
                    <DatePicker placeholder="请选择日期" style={{ width: '100%' }} />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="收件手机" colon={false}>
                  {getFieldDecorator('consigneePhone')(
                    <Input allowClear type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="批次编号" colon={false}>
                  {getFieldDecorator('seqNo')(
                    <InputNumber
                      min={0}
                      step={1}
                      precision={0}
                      placeholder="请输入"
                      style={{ width: '100%' }}
                    />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Item label="投递手机" colon={false}>
                  {getFieldDecorator('courierPhone')(
                    <Input type="number" placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="id"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            scroll={{ x: 1500 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<OrderInfoProps>()(OrderInfoElem);
